<?php

namespace Frieza\Modules\Article\Controllers;

use Biz\model\wiki\ObjRelateWiki as mObjRelateWiki;
use Biz\service\wiki\ObjRelateWiki;
use Doraemon\model\Article;
use Doraemon\tools\Creator\GrowthConfig as tGrowthConfig;
use Hhz\AdministrativeRegion\Region;
use App\Admin\Extensions\WorkContent;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\pockets\excel\DownExcel;
use Doraemon\amqp\CommunityLevelQueue;
use Doraemon\amqp\CommunityQueue;
use Doraemon\cache\ArticleCounter;
use Doraemon\cache\JudgeArticle;
use Doraemon\cache\Photos as cPhotos;
use Doraemon\cache\Queue;
use Doraemon\model\AdminAccount\AdminAccount;
use Doraemon\model\AdminAccount\AdminAccountOperate;
use Doraemon\model\AdmNoteOutlineLog;
use Doraemon\model\AdmNoteRemark;
use Doraemon\model\Article as dbArticle;
use Doraemon\model\BestArticle;
use Doraemon\model\Comment as DbComment;
use Doraemon\model\ContentRecommendTags\ContentRecommendTags;
use Doraemon\model\ContentSignExtend;
use Doraemon\model\Member;
use Doraemon\model\MyArticleList;
use Doraemon\model\Photos as dbPhoto;
use Doraemon\model\RecommendArticle;
use Doraemon\service\AdmArticle\ArticleSearch;
use Doraemon\service\AdmArticle\FilterConfig;
use Doraemon\service\AdmArticle\Schedule;
use Doraemon\service\AdmNote;
use Doraemon\service\Article as sArticle;
use Doraemon\service\BindDesignerArticle as sBindDesignerArticle;
use Doraemon\service\Creators\LevelStandard as sLevelStandard;
use Doraemon\service\IntelligentRecommend\HaveRecommend;
use Doraemon\service\Member as sMember;
use Doraemon\service\Note\NoteHandle;
use Doraemon\service\UserGrowth\AutoAction;
use Doraemon\tools\BlockType;
use Doraemon\tools\HhzNiceLivingUrl;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\IdParse;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Ip;
use Doraemon\tools\Log;
use Doraemon\tools\PointConfig;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Frieza\Modules\Position\Controllers\UserProfileListController;
use Hhzbeads\Point\PointClient;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\cache\Article as cArticle;

class ArticleSelectController extends Controller
{

    const NOT_IN_HAPPY_ACTIVITY_SCORE = 65;

    const FINE_SCORE = 70; // 优秀

    const ORDINARY_SCORE = 60; //普通

    const NOT_FINE_SCORE = 5;//差

    const FINE_MSGCODE = 230;

    const ORDINARY_MSGCODE = 228;

    const NOT_FINE_MSGCODE = 227;

    const OBJ_TYPE = BlockType::TYPE_ARTICLE;

    const ES_BUSINESS = [
        "NOT_BUSINESS" => 0,
        "SOFT_BUSINESS" => 1,
        "HARD_BUSINESS" => 2
    ];

    const NORMAL_WORD = '/home/adm_rsync_dir/article_common_remark.txt';

    // 所有用户类型
    const ALL_USER_TYPE = array(
        Member::USER_COMMON,
        Member::AUTH_USER_V,
        Member::AUTH_ORG_V,
        Member::AUTH_USER_STORE,
    );
    public static $typeDesc = [
        Member::USER_COMMON => '普通用户',
        Member::AUTH_USER_V => '个人V认证',
        Member::AUTH_ORG_V => '机构V认证',
        Member::AUTH_USER_STORE => '营造家门店',
    ];

    public function __construct(Request $request)
    {
        parent::__construct();

    }

    public function index(Request $request, Content $content)
    {
        Admin::script(
            <<<EOF
        $('input[type=radio][name=select_area]').on('ifChecked',function(){
            if(this.value == 1) {
                $("select.multiplearea").parent().parent().hide();
                $("select.province").parent().parent().show();
                $("select.city").parent().parent().show();
            }else {
                $("select.multiplearea").parent().parent().show();
                $("select.city").parent().parent().hide();
                $("select.province").parent().parent().hide();
            }
        });
        
        $('input[type=radio][name=is_audit_again]').on('ifChecked',function(){
            if(this.value == 0) {
                $("select.audit_time").parent().parent().hide();
            }else {
                $("select.audit_time").parent().parent().show();
        
            }
        });
        $('input[type=radio][name=select_area]:checked').trigger('ifChecked');
        
        console.log($('.Find-filter-group-label').val());
        
EOF
        );

        Admin::style('.column-title {width:15%;}');

        $url = $_SERVER["REQUEST_URI"];
        $data_url = explode('?', $url);
        $export_url = $data_url[1] ?: '';

        Admin::script($this->setScript());
        $requestParams = $request->all();

        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $requestParams['page_size'] = $pageSize;
        $requestParams['page'] = $page;
        if (empty($requestParams['article_id'])) {
            $requestParams['user_type'] = $requestParams['user_type'] ?? self::ALL_USER_TYPE;
            $object = new ArticleSearch($requestParams);
            $solr_list = Schedule::getList($object);
            $article_ids = $solr_list['rows'] ?: [];
            if ($requestParams['nick'] && $object->uid == 0) {
                $article_ids = [];
            }
        } else {
            $article_ids = [$requestParams['article_id']];
        }


        $list = [];
        if ($article_ids && is_array($article_ids)) {
            $list = dbArticle::select("*", [
                "AND" => [
                    "aid" => $article_ids,
                    "status" => [
                        dbArticle::STATUS_WAIT_CHECK,
                        dbArticle::STATUS_SUCCESS,
                    ]
                ],
                'ORDER' => ['publish_time' => 'DESC']
            ]);

            //按照aiticle_id 排序
            $info = sArticle::getArticleBasicInfos($article_ids);
        }

        // 获取整屋案例重复情况
        $hashSameArticleInfos = JudgeArticle::multiGetSameInfos($article_ids);
        //运营评论列表
        $admin_comments = [];
        $comments = AdminAccountOperate::getByObjIds($article_ids, AdminAccountOperate::ACCOUNT_TYPE_COMMENT, self::OBJ_TYPE);
        if ($comments && is_array($comments)) {
            foreach ($comments as $comment) {
                $admin_comments[$comment['obj_id']] = (string)Admin::user()->find($comment['admin_id'])->name;
            }
        }
        //运营点赞列表
        $admin_likes = [];
        $likes = AdminAccountOperate::getByObjIds($article_ids, AdminAccountOperate::ACCOUNT_TYPE_LIKE, self::OBJ_TYPE);
        if ($likes && is_array($likes)) {
            foreach ($likes as $like) {
                $admin_likes[$like['obj_id']] = (string)Admin::user()->find($like['admin_id'])->name;
            }
        }

        $extendMap = [];
        $extendInfo = ContentSignExtend::getExtendInfoByNoteIds($article_ids);
        if ($extendInfo && is_array($extendInfo)) {
            foreach ($extendInfo as $value) {
                $extendMap[$value['obj_id']] = $value;
            }
        }

        $total = $solr_list['total'];
        $userProfile = new UserProfileListController();
        if ($list && is_array($list)) {
            foreach ($list as &$val) {
                $val['cover_img_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $val['cover_pic_id'], ImgUrl::IMAGE_SIZE_O_500);
                $val['admin_tag'] = array_filter(explode(",", $val['admin_tag'])) ?: [];
                if ($info[$val['aid']] && is_array($info[$val['aid']])) {
                    $val['area_name'] = $info[$val['aid']]['article_info']['area_name'];
                    $val['like'] = $info[$val['aid']]['counter']['like'];
                    $val['favorite'] = $info[$val['aid']]['counter']['favorite'];
                    $val['comments'] = $info[$val['aid']]['counter']['comments'];
                    $val['read'] = $info[$val['aid']]['counter']['read'];
                    $val['nick'] = $info[$val['aid']]['user_info']['nick'];
                    $val['house_size'] = $info[$val['aid']]['article_info']['house_size'];
                    $val['house_stuff'] = $info[$val['aid']]['article_info']['house_stuff'] / 10000;
                    $val['house_construction'] = $info[$val['aid']]['article_info']['house_construction'];
                    if ($val['title'] != $info[$val['aid']]['article_info']['title']) {
                        $val['op_title'] = $info[$val['aid']]['article_info']['title'];
                    }
                    $val['user_type'] = $userProfile->FormateType($info[$val['aid']]['user_info']['uid'], $info[$val['aid']]['user_info']['type']);
                    $adm_info = $userProfile->FormateUserTag($info[$val['aid']]['user_info']['uid']);
                    $val['user_tag'] = $adm_info['user_tag'];
                    $val['quality'] = $adm_info['user_quality'];
                }


                if ($val['admin_score'] > 0 && $val['status'] == 1) {
                    $val['audit_status'] = 1;
                }
                if ($val['status'] == dbArticle::STATUS_WAIT_CHECK && $val['admin_score'] > 0) {
                    $val['audit_status'] = dbArticle::STATUS_WAIT_CHECK;
                }
                if ($val['status'] = dbArticle::STATUS_WAIT_CHECK && $val['admin_score'] == 0) {
                    $val['audit_status'] = 2;
                }

                $val['audit_status'] = FilterConfig::ARTICLE_STATUS[$val['audit_status']];
                $extend_info = json_decode($val['extend'], true) ?: [];
                if ($extend_info && is_array($extend_info)) {
                    $room_ids = $extend_info['live_room_ids'] ?: [];
                    if ($room_ids && is_array($room_ids)) {
                        $val['room_ids'] = implode(',', $room_ids);
                    }
                }

                // 案例重复信息
                $val['same_infos'] = array();
                if (isset($hashSameArticleInfos[$val['aid']]) && $hashSameArticleInfos[$val['aid']]) {
                    $sameInfos = json_decode($hashSameArticleInfos[$val['aid']], true);
                    $val['same_infos'] = $sameInfos;
                }
                //运营相关操作
                $val['admin_comment'] = (string)$admin_comments[$val['aid']];
                $val['admin_like'] = (string)$admin_likes[$val['aid']];
                $val['is_business'] = $extendMap[$val['aid']]['is_business'] ?: 0;
                $val['is_display_business'] = $extendMap[$val['aid']]['is_display_business'] ?: 0;
            }
        }

        $gridModel = new pGridDataModel($list, $total, [

            'perPage' => $pageSize
        ]);

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $export_url) {
                $grid->paginate($gridModel->getPerPage());
                //筛选
                $grid->disableExport();
                $grid->tools(function ($tools) use ($export_url) {
                    $url = url('/admin/article/select/exportNormarlData?' . $export_url);
                    $button = '<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" title="导出" target="_blank" href="' . $url . '"><i class="fa fa-download"></i><span class="hidden-xs"> 导出</span></a>
</div>';
                    $tools->append($button);
                });
                //筛选
                $grid->filter(function (\Encore\Admin\Grid\Filter $filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();

                    $filter->column(1 / 2, function ($filter) {
                        $filter->dropDown('Find', [
                            'article_id' => '文章id',
                            'uid' => 'uid',
                            'nick' => '用户昵称',
                            'title' => "文章标题",
                            'op_title' => '运营精选标题',
                            'adm_remark' => '文章备注',
                            'admin_tag' => '文章标签'
                        ]);
                        $filter->equal('user_type', '用户身份')->checkbox(self::$typeDesc);
                        $filter->equal('confirmed', '用户标识')->checkbox(FilterConfig::USER_TYPE);
                        $filter->equal('quality', '用户质量')->checkbox(FilterConfig::QUALITY);

                        $filter->equal('high_check', '高级筛选')->checkbox(FilterConfig::HIGH_CHECK);

                        $filter->equal('score', '分数')->checkbox(FilterConfig::SCORE);
                        $filter->equal('tag_status', '标签状态')->radio(FilterConfig::TAG_STATUS);
                        $filter->equal('audit_status', '审核状态')->radio(FilterConfig::AUDIT_AGAIN)->default(0);
                    });

                    $filter->column(1 / 2, function ($filter) {
                        $filter->between('release_time', '发布时间')->datetime();
                        $filter->between('user_update_time', '用户编辑时间')->datetime();
                        $filter->between('size', '面积大小');
                        $filter->between('stuff', '预算');


                        $filter->equal('room', '居室')->checkbox(FilterConfig::ROOM);
                        $filter->equal('business', '商业')->radio(FilterConfig::BUSINESS);
                        $top = Region::getProvincesList();
//                        $top = Area::getLocation();
//                        $filter->equal('select_area', '地区')->radio([
//                            0    => '地区多选(支持到省和直辖市)',
//                            1    => '地区单查(支持到市、区)',
//                        ])->default(1);
                        $filter->in('multiplearea', '地区(多选)')->multipleSelect($top);
//                        $filter->equal('province', '省')->select(FilterConfig::getLoaction())->load('city', route('article.area'));
//                        $filter->equal('city', '市、区')->select();
                        $filter->equal('is_have_repeat', '只看疑似重复案例')->checkbox(FilterConfig::IS_HAVE_REPEAT);
                    });
                    //条件展开
                    $filter->expand();

                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->expandFilter();

                $grid->column("aid", 'id')->display(function () {
                    $display = [];
                    $display[] = '<a href="/admin/article/select/audit/' . $this->aid . '" target="_blank">' . $this->aid . '</a>';

                    return implode('<br/>', $display);


                })->width(200);
                $grid->column('uid', '用户信息')->userBasicInfo()->width(150);
                $grid->column('admin_comment', '额外信息')->display(function () {
                    if (empty($this->admin_comment)) {
                        $comment_btn = "<a href='javascript:;' class='btn btn-default addComment'  data-id='$this->aid' id='$this->aid'>运营评论</a>";
                    } else {
                        $comment_btn = "<a href='javascript:;' class='btn btn-success'  data-id='$this->aid' id='$this->aid'>$this->admin_comment 已评论</a>";
                    }
                    if (empty($this->admin_like)) {
                        $like_btn = "<a href='javascript:;' class='btn btn-default addLike'  data-id='$this->aid' id='like$this->aid'>运营点赞</a>";
                    } else {
                        $like_btn = "<a href='javascript:;' class='btn btn-success'  data-id='$this->aid' id='like$this->aid'>$this->admin_like 已点赞</a>";
                    }
                    $copy_btn = "<a href='javascript:;' class='btn btn-default copyH5'  data-id='$this->aid' >复制链接</a>";
                    if ($this->is_business) {
                        $businessBtn = "<a href='javascript:;' class='btn btn-success addBusiness'  data-id='$this->aid' id='business$this->aid'>软广</a>";
                    } else {
                        $businessBtn = "<a href='javascript:;' class='btn btn-default addBusiness'  data-id='$this->aid' id='business$this->aid'>软广</a>";
                    }
                    if ($this->is_display_business) {
                        $displayBusiness = "<a href='javascript:;' class='btn btn-success addDisplayBusiness'  data-id='$this->aid' id='displayBusiness$this->aid'>硬广</a>";
                    } else {
                        $displayBusiness = "<a href='javascript:;' class='btn btn-default addDisplayBusiness'  data-id='$this->aid' id='displayBusiness$this->aid'>硬广</a>";
                    }
                    if (Admin::user()->isRole('partime.user')) {
                        return $comment_btn . "<br><br>" . $like_btn . "<br><br>" . $copy_btn;
                    }
                    if (Admin::user()->isRole('coc.business_create_op') || Admin::user()->isRole('coc.business_cooperate')){
                        return $comment_btn . "<br><br>" . $like_btn . "<br><br>" . $copy_btn . "<br><br>" . $businessBtn. "<br><br>" . $displayBusiness;
                    }
                    return $comment_btn . "<br><br>" . $like_btn . "<br><br>" . $copy_btn . "<br><br>" . $businessBtn;
                })->width(150);
                $grid->column('admin_tag', '文章标签')->display(function () {
                    $options = '';
                    if ($this->admin_tag && is_array($this->admin_tag)) {
                        foreach ($this->admin_tag as $tag) {
                            $options = $options . '<button style="display:inline-block;margin:2px;" class="marktag btn btn-sm btn-primary" data-had="">' . $tag . '</button><br/>';
                        }
                    }
                    return $options;
                })->width(200);
                $grid->column("title", '文章信息')->display(function () {
                    $display = [];
                    $display[] = "<span style='font-size: 15px;width:10px; white-space:pre-wrap;'>标题:<b>" . $this->title . "</b></span>";
                    // $display[] ="<p style='font-size: 15px;width: 30px;  white-space:pre-wrap;'>标题:".$this->title."</p>" ;
                    if ($this->op_title) {
                        $display[] = "<sapn style='font-size: 15px'>精选标题:<b>" . $this->op_stitle . "</b></sapn>";
                    }
                    $display[] = "<sapn style='font-size: 15px'>使用面积:<b>" . $this->house_size . "</b>平米</sapn>";
                    $display[] = "<sapn style='font-size: 15px'>位置:<b>" . $this->area_name . "</b></sapn>";
                    $display[] = "<sapn style='font-size: 15px'>预算:<b>" . $this->house_stuff . "</b>万元</sapn>";
                    $display[] = "<sapn style='font-size: 15px'>居室:<b>" . FilterConfig::ROOM[$this->house_construction] . "</b></sapn>";

                    return implode('<br/>', $display);
                })->width(200);

                $grid->column("interact", '交互')->display(function () {
                    $display = [];
                    $display[] = "<sapn style='font-size: 15px'>点赞:<b>" . $this->like
                        . "</b></sapn>";
                    $display[] = "<sapn style='font-size: 15px'>收藏:<b>" . $this->favorite . "</b></sapn>";
                    $display[] = "<sapn style='font-size: 15px'>评论:<b>" . $this->comments . "</b></sapn>";

                    return implode('<br/>', $display);
                })->width(200);

                $grid->column('publish_time', '首发时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->publish_time);
                });
                $grid->column('user_update_time', '用户编辑时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->user_update_time);
                });

                $grid->column('same_infos', '疑似重复案例')->display(function () {
                    $str = "";
                    foreach ($this->same_infos as $aid => $sameInfo) {
                        $articleDetailUrl = "/admin/article/select/audit/" . $aid;
                        $str .= "案例id:<a href='{$articleDetailUrl}'  target='_blank' >{$aid}</a>:重复占比{$sameInfo['same_rate']}";
                    }
                    return $str;
                });

                $grid->column('admin_score', '分数')->display(function () {
                    $display[] = '<p style="white-space:nowrap">' . FilterConfig::SCORE_CONTENT[$this->admin_score] . $this->admin_score . '</p>';

                    if (Admin::user()->can('article-Audit-D')) {
                        $url = '/admin/article/select/bestForm/' . $this->aid;

                        $display[] = '<a href="javascript:layer.open({
                                type: 2,
                                title: \'精选\',
                                maxmin: true,
                                area: [\'400px\', \'500px\'],
                                content: \'' . $url . '\'
                            });"    data-score="80" class="label  grade_2 label-info"> 精选  </a><br/>';
                        if ($this->admin_score > 70) {

                            $display[] = '<a class="	delbest label  label-default" data-id="' . $this->aid . '"  href="javascript:void(0);">取消精选</a>';

                        }
                    }
                    return implode('<br/>', $display);


                })->width(200);;

                $grid->column('audit_status', '审核')->display(function ($title, Grid\Column $column) {
                    if ($this->audit_status == '已审核') {
                        return $column->label('success');
                    } else if ($this->audit_status == '未审核') {
                        return $column->label('warning');
                    } else if ($this->audit_status == '待复审') {
                        return $column->label('danger');
                    }
                });


                $grid->column('admin_name', '操作人')->display(function () {
                    if (!$this->admin_name) {
                        return '暂无';
                    } else {
                        return $this->admin_name;
                    }
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $url = 'https://m.haohaozhu.cn/bangyang/' . $actions->row->aid . '.html?preview=1';
                    $actions->prepend('<p style="white-space:nowrap"><a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $url . '\'
                            });">预览  </a></p>');

                    if (Admin::user()->can('article-Audit-C')) {
                        $actions->prepend('<p><a class="	del label  label-info" data-id="' . $actions->row->aid . '"  href="javascript:void(0);">删除</a></p>');
                        $actions->prepend('<p><a class="	setPrivate label  label-info" data-id="' . $actions->row->aid . '"  href="javascript:void(0);">设置仅自己可见</a></p>');
                    }


                });

            });

        $tab = new Tab();
        $tab->add('整屋列表', $gridList->render());


        $tab->addLink('违规整屋', url('/admin/article/select/draftlist'));
        $tab->addLink('编辑常用语', url('/admin/article/select/normalword/list'));

        Admin::script($this->commentPopup());
        Admin::script($this->adminLike());
        Admin::script($this->adminCopy());
        $content->row($tab);

        return $content
            ->header('整屋')
            ->description(' ')
            ->breadcrumb(
                ['text' => '整屋列表', 'url' => '/article/select/index']
            );
    }


    /*draft article
     *
     * */
    public function draftlist(Request $request, Content $content)
    {
        Admin::script(
            <<<EOF
              //仅自己可见
         $('.recoverPrivateOfArticle').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要恢复全局可见么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/article/select/recoverPrivateOfArticle/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.status == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
        
EOF
        );

        $requestParams = $request->all();

        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        if (isset($requestParams['Find_group']) && $requestParams['Find']) {
            $requestParams[FilterConfig::ARTICLE_FIND_GROUP[$requestParams['Find_group']]] = $requestParams['Find'];
        }
        $map = ['ORDER' => ['addtime' => 'DESC']];

        if ($requestParams['nick']) {
            $uid = Member::getUidByNick($requestParams['nick']);
            if ($uid) {
                $map['AND']['uid'] = $uid;
            }
        }
        if ($requestParams['uid']) {
            $map['AND']['uid'] = $requestParams['uid'];
        }
        if ($requestParams['article_id']) {
            $map['AND']['aid'] = $requestParams['article_id'];
        }
        if ($requestParams['title']) {
            $map['AND']['title[~]'] = $requestParams['title'];
        }
        if ($requestParams['adm_remark']) {
            $map['AND']['adm_remark[~]'] = $requestParams['adm_remark'];
        }

        if ($requestParams['addtime']['start'] && $requestParams['addtime']['end']) {
            $map['AND']['addtime[<>]'] = [strtotime($requestParams['addtime']['start']), strtotime($requestParams['addtime']['end'])];
        }
        $status = [
            dbArticle::STATUS_PRIVATE,
            dbArticle::STATUS_DELETE,
            dbArticle::STATUS_DRAFT,
            dbArticle::STATUS_FIRST_EDIT,
            dbArticle::STATUS_FORCE_OUT,
            dbArticle::STATUS_ONE_KEY_DRAFT
        ];
        if ($requestParams['status']) {
            //草稿
            if ($requestParams['status'] == 1) {
                $status = [
                    dbArticle::STATUS_DRAFT,
                    dbArticle::STATUS_FIRST_EDIT,
                    dbArticle::STATUS_ONE_KEY_DRAFT
                ];
            }
            //封杀
            if ($requestParams['status'] == 2) {
                $status = [
                    dbArticle::STATUS_FORCE_OUT,
                ];
            }

            //删除
            if ($requestParams['status'] == 3) {
                $status = [
                    dbArticle::STATUS_DELETE,
                ];
            }
            //仅自己可见
            if ($requestParams['status'] == 4) {
                $status = [
                    dbArticle::STATUS_PRIVATE,
                ];
            }
        }

        $map['AND']['status'] = $status;
        $total = dbArticle::count($map);
        $map['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $list = dbArticle::select("*", $map);

        $uids = array_column($list, 'uid');
        $user_info = sMember::getUserInfoByUserIds($uids);
        if ($list && is_array($list)) {
            foreach ($list as &$val) {
                $val['nick'] = $user_info[$val['uid']]['nick'];
            }
        }
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $export_url = '';
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $export_url) {
                $grid->paginate($gridModel->getPerPage());
                //筛选
                $grid->disableExport();
//                $grid->tools(function ($tools) use ($export_url) {
//                    $url = url('/admin/position/userProfile/exportData?'.$export_url);
//                    $button = '<div class="btn-group download" style="margin-right: 10px">
//    <a class="btn btn-sm btn-twitter" title="导出" target="_blank" href="'.$url.'"><i class="fa fa-download"></i><span class="hidden-xs"> 导出</span></a>
//</div>';
//                    $tools->append($button);
//                });
                //筛选
                $grid->filter(function (\Encore\Admin\Grid\Filter $filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->group('Find', function ($group) {
                        $group->equal('文章id');
                        $group->equal('uid');
                        $group->equal('用户昵称');
                        $group->equal("文章标题");
                        $group->equal("文章备注");

                    });
                    $filter->equal('status', '文章状态')->radio(FilterConfig::STATUS_NONORMAL)->default(0);
                    $filter->between('addtime', '创建时间')->datetime();
                    //条件展开
                    $filter->expand();
                });

                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->expandFilter();
                $grid->fixColumns(0, -4);

                $grid->column("aid", 'id')->display(function () {
                    $display = [];
                    $display[] = '<a href="/admin/article/select/audit/' . $this->aid . '" target="_blank">' . $this->aid . '</a>';
                    $display[] = "<sapn style='font-size: 15px'>uid:<b>" . $this->uid . "</b></sapn>";
                    $display[] = "<sapn style='font-size: 15px'>昵称:<b>" . $this->nick . "</b></sapn>";
                    return implode('<br/>', $display);


                });
                $grid->column("title", '文章信息')->display(function () {
                    $display = [];
                    $display[] = "<sapn style='font-size: 15px'>标题:<b>" . $this->title . "</b></sapn>";
                    if ($this->publish_time) {
                        $display[] = "<sapn style='font-size: 15px'>发布时间:<b>" . date('Y-m-d H:i:s', $this->publish_time) . "</b></sapn>";

                    }
                    if ($this->adm_remark) {
                        $display[] = "<sapn style='font-size: 15px'>备注:<b>" . $this->adm_remark . "</b></sapn>";
                    }

                    return implode('<br/>', $display);


                });

                $grid->column('status', '状态')->display(function ($title, Grid\Column $column) {
                    $display = [];
                    if ($this->status == dbArticle::STATUS_DRAFT || $this->status == dbArticle::STATUS_FIRST_EDIT || $this->status == dbArticle::STATUS_ONE_KEY_DRAFT) {

                        $display[] = '<a class=" label  label-default" data-id="' . $this->aid . '"  href="javascript:void(0);">草稿</a>';
                    } elseif ($this->status == dbArticle::STATUS_FORCE_OUT) {
                        $display[] = '<a class=" label  label-danger" data-id="' . $this->aid . '"  href="javascript:void(0);">后台删除</a>';

                    } elseif ($this->status == dbArticle::STATUS_DELETE) {
                        $display[] = '<a class=" label  label-info" data-id="' . $this->aid . '"  href="javascript:void(0);">删除</a>';

                    } elseif ($this->status == dbArticle::STATUS_PRIVATE) {
                        $display[] = '<a class=" label  label-success" data-id="' . $this->aid . '"  href="javascript:void(0);">仅自己可见</a>';
                    }
                    return implode("<br/>", $display);


                });

                $grid->column('admin_id', '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '暂无';
                    } else {
                        //  return Admin::user()->find($this->admin_id)->name;
                    }
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $url = 'https://m.haohaozhu.cn/bangyang/' . $actions->row->aid . '.html?preview=1';
                    $actions->prepend('<p style="white-space:nowrap"><a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $url . '\'
                            });">预览  </a></p>');

                    if ($actions->row->status == dbArticle::STATUS_PRIVATE) {
                        $actions->prepend('<a class="fa fa-adjust recoverPrivateOfArticle" data-id="' . $actions->row->aid . '"  href="javascript:void(0);">设置全部可见  </a>');

                    }
                });
            });

        $tab = new Tab();
        $tab->addLink('整屋列表', url('/admin/article/select/index'));

        $tab->add('违规整屋', $gridList->render(), true);
        $tab->addLink('编辑常用语', url('/admin/article/select/normalword/list'));
        $content->row($tab);
        return $content
            ->header('整屋')
            ->description(' ')
            ->breadcrumb(
                ['text' => '整屋列表', 'url' => '/article/select/index']
            );
    }


    /**
     * 审核
     */
    public function audit(Request $request, Content $content, $aid)
    {
        Admin::style('.content-wrapper {margin-left:0px;}');
        Admin::style('.main-sidebar {display:none;}');
        Admin::style('.main-header {display:none;}');
        Admin::style('.form-horizontal {margin-left:-20%;}');
        Admin::script(
            <<<EOF
          //使用常用语
           $('.normalword').on('change',function(){
            var option = $(this).val();
            var remark=  $(".remark").val()
            $(".remark").val(remark+option);       
         });
         //一键复审
         $('.reCheck').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定一键复审么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/article/select/reCheck/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.status == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
EOF
        );
        return $content
            ->header('整屋审核')
            ->breadcrumb(
                ['text' => "审核"]
            )
            ->row(function (Row $row) use ($aid) {
                $row->column(9, $this->H5($aid));
                $row->column(3, $this->auditForm($aid));
            });
    }


    public function H5($aid)
    {
        $form = new Form();
        $form->disableReset();
        $form->disableSubmit();
        $url = 'https://m.haohaozhu.cn/bangyang/' . $aid . '.html?preview=1';
        $form->html('<iframe src="' . $url . '" style="width:100%; height:1000px;margin-top:10px;"></iframe>');

        return $form->render();
    }

    public function auditForm($aid)
    {
        Admin::script($this->setScript());
        $info = dbArticle::getArticle($aid);
        $best_info = BestArticle::getOneArticle($aid);
        $recommend_tags = ContentRecommendTags::getByObjIdAndTagType($aid, ContentRecommendTags::TAG_TYPE_STYLE);
        $word = self::getNormalWord();
        $designerTagTemp = [];
        $designerTagStr = '';
        if ($info && is_array($info)) {
            $info['tags'] = array_filter(explode(",", trim($info['admin_tag']))) ?: [];
            if (!empty($info['designer_tag'])) {
                $designerTag = json_decode($info['designer_tag'], true);
                if (is_array($designerTag)) {
                    foreach ($designerTag as $key =>$item) {
                        if($key == 'pet'){
                            $item ='宠物生活设计';
                        }
                        $designerTagTemp = array_merge($designerTagTemp, explode(',', $item));
                    }
                }
            }
            
            if ($best_info && is_array($best_info)) {
                $info['op_title'] = $best_info['title'];
            }
            $info['op_status'] = $info['status'];
            $info['remark'] = $info['adm_remark'];
        }

        if (!empty($designerTagTemp)) {
            $designerTagStr = implode(',', $designerTagTemp);
        }
        $tags = explode("\n", file_get_contents('/home/adm_rsync_dir/tags/adm_tags_all'));
        // 因为标签栏里是前端排序，要把用户的标签置前，这个地方以后可能会出问题。成立的条件是算法的标签要在配置文件内
        $tags = array_merge($info['tags'], $tags);
        if ($tags && is_array($tags)) {
            $tags = array_combine($tags, $tags);
        }
        $form = new Form($info);
        if (Admin::user()->can('article-Audit-D')) {
            $url = '/admin/article/select/bestForm/' . $aid;
            $form->html('<a href="javascript:layer.open({
                                type: 2,
                                title: \'精选\',
                                maxmin: true,
                                area: [\'400px\', \'500px\'],
                                content: \'' . $url . '\'
                            });"    data-score="80" class="label  grade_2 label-info"> 精选  </a><br/>');
            if ($info['admin_score'] > 70) {
                $form->html('<a class="	delbest label  label-default" data-id="' . $aid . '"  href="javascript:void(0);">取消精选</a>');

            }
        }
        if (Admin::user()->can('article-Audit-A') && $info['status'] == dbArticle::STATUS_WAIT_CHECK && $info['admin_score'] > 0) {
            $form->html('<a href="javascript:void(0)" data-id="' . $info['aid'] . '" class="label label-info reCheck">一键复审</a>');
        }

        $form->hidden('aid');
        if (Admin::user()->can('article-Audit-B')) {
            $form->multipleSelect("tags", '标签')->options($tags)->load('tag', route("article.tag"))->help('用户标签：'.$designerTagStr);
            $form->html('<span class="help-block"><i class="fa fa-info-circle"></i>&nbsp;算法标签： '.$recommend_tags['recommend_tags'].'</span>');
        }
        if (Admin::user()->can('article-Audit-A')) {
            if ($info['admin_score'] <= 70) {
                $form->fieldChange('admin_score', '打分', $form)
                    ->options([
                        '0' => '未打分',
                        '5' => '差',
                        '60' => '普通',
                        '70' => "优秀",
                    ])
                    ->default(0)
                    ->callablePreCommon(function (Form $form) {
                    })->callableMap([
                        0 => function (Form $form) {
                        },
                        5 => function (Form $form) {
                        },
                        60 => function (Form $form) {
                        },
                        70 => function (Form $form) {
                        },
                    ]);
            } else {
                $form->html('<span>精选文章<span/>', '分数');
            }

        }
        $form->imgUpload('list_cover_id', '竖图', false, ['imgType' => ImgUrl::APPTYPE_APP, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE])->readonly();
        $form->textarea('remark', "备注");
        $form->select('normalword', '备注常用语')->options($word)->default('-1')->help('仅为后台备注使用');
        $send_url = '/admin/article/select/sendMsgForm/' . $aid;
        $form->html('<a href="javascript:layer.open({
                                type: 2,
                                title: \'发送下行\',
                                scrollbar: false,
                                maxmin: true,
                                area: [\'400px\', \'500px\'],
                                content: \'' . $send_url . '\'
                            });"  class="label grade_2 label-info"> 发送下行  </a><br/>');

        $form->action('/admin/article/select/audit/save');
        $form->disableReset();
        return $form->render();
    }


    /*获取常用语
     *
     * */
    public static function getNormalWord()
    {
        $result = [
            '-1' => '选择常用语',
        ];
        $word = array_map('trim', explode("\n", file_get_contents('/home/adm_rsync_dir/article_common_remark.txt')));
        foreach ($word as $key => $value) {
            $result[$value] = $value;
        }
        return $result;
    }


    /*保存审核内容
     *
     * */
    public static function auditSave(Request $request)
    {

        try {
            $request = $request->all();
            $aid = $request['aid'];
            $info = dbArticle::getInfosByAids($aid);
            if (empty($info)) {
                throw new \Exception('文章不存在！');
            }
            $score = $request['admin_score'] ?: 0;
            $remark = $request['remark'] ?: '';
            $tags = [];
            if (isset($request['tags'])) {
                $tags = array_unique(array_filter($request['tags']));
            }

            $admin_tag = '';
            if ($tags && is_array($tags)) {
                $admin_tag = implode(",", $tags);
            }
            $update_data = [];
            if ($score) {
                $update_data['admin_score'] = $score;
                $update_data  ['status'] = dbArticle::STATUS_SUCCESS;
                $update_data  ['check_time'] = time();
            }

            $update_data['adm_remark'] = $remark;

            $update_data['admin_tag'] = $admin_tag;


            //更新算法标签
            $recommend_tags = ContentRecommendTags::getByObjIdAndTagType($aid);
            if ($recommend_tags && is_array($recommend_tags)) {
                $old_recommend_tags = explode(',', $recommend_tags['recommend_tags']);
                $diff = array_diff($old_recommend_tags, explode(',', $update_data['admin_tag']));
                if ($diff && is_array($diff)) {
                    $bad_tags = array_merge(explode(',', $recommend_tags['bad_tags']), $diff);
                    $bad_tags = array_unique(array_filter($bad_tags));
                    ContentRecommendTags::update(['bad_tags' => implode(',', $bad_tags
                    )], ['obj_id' => $aid, 'tag_type' => ContentRecommendTags::TAG_TYPE_STYLE]);
                }
            }

            // 查询更新之前此整屋的质量
            $qualityLastTime = -1;
            if ($info[0]['admin_score'] != $score) {
                $qualityLastTime = $info[0]['admin_score'];
            }

            $update_data['admin_id'] = Admin::user()->id;
            $update_data['admin_name'] = Admin::user()->name;
            $rs = dbArticle::updateArticle($aid, $update_data);

            //审核
            if ($rs) {
                $reason = '更改tag为:' . $admin_tag . ', 分数为:' . $score;
                AdmNote::auditLog($aid, dbPhoto::QUALITY_LOW, Admin::user()->name, AdmNoteOutlineLog::AUDIT_CHANNEL_ARTICLE, $reason);
                Log::info('整屋审核操作', [$update_data, $request, Admin::user()->name]);
                Queue::insertQueue("TotalArticle/updateTotalArticle", ['article_id' => $aid]);
                cArticle::delete($aid);
                Queue::insertQueue('Article/updateSolr', ['article_id' => $aid]);
                self::pushLevel3Standard($aid, $qualityLastTime, $score);
                if ($score > 10) {
                    //如果打分高于10分，投wiki队列
                    \Doraemon\amqp\Queue::insertQueue('queue/wiki/afterAuditContent', array(
                        'obj_id' => $aid,
                    ), \Doraemon\amqp\Queue::QUEUE_BIZ);
                }

                $success = new MessageBag([
                    'title' => '操作成功'
                ]);
                //发送审核消息
                return redirect('/admin/article/select/audit/' . $aid)->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return redirect('/admin/article/select/audit/' . $aid)->with(compact('error'));
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return redirect('/admin/article/select/audit/' . $aid)->with(compact('error'));
        }


    }


//    public function area(Request $request)
//    {
//        $pid = $request->input('q', 0);
//        $areas = Area::getLocation($pid);
//        $format = array_map(function ($k, $v) {
//            return [
//                'id' => $k,
//                'text' => $v,
//            ];
//        }, array_keys($areas), $areas);
//        return response()->json($format);
//    }


    /*精选框
     *
     * */
    public function bestForm(Request $request, Content $content, $aid)
    {
        Admin::style('.main-header {display:none;}');
        $best_info = BestArticle::getOneArticle($aid);
        $best_info = $best_info ?: [];
        $best_info['aid'] = $aid;
        $form = new Form($best_info);
        $form->hidden('aid', 'aid');
        $form->text('title', '标题');
        $form->disableReset();
        $form->action('/admin/article/select/addBest');
        return $content->row($form->render());
    }

    public function sendMsg(WorkContent $content, $aid)
    {
        $info['aid'] = $aid;
        $info['uid'] = IdParse::getUid($aid);
        $form = new Form($info);
        $form->textarea('send_msg', "下行消息");
        $form->hidden('aid', 'aid');
        $form->hidden('uid', 'uid');
        $form->action('/admin/article/select/pushMsg');
        return $content->row($form->render());
    }

    public function pushMsg(Request $request)
    {
        $info = $request->input();
        if ($info['aid'] != '' && $info['send_msg'] != '') {
            $link = HhzNiceLivingUrl::getArticleDetailLink($info['aid']);
            Queue::insertQueue('queue/Sysmsg/Send', [
                'msgCode' => 0,
                'to_uid' => $info['uid'],
                'msgParams' => [
                    'article_id' => $info['aid'],
                    'detail' => $info['send_msg'],
                    'link' => $link
                ]
            ], Queue::QUEUE_DORAEMON);
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return back()->with(compact('success'));
        }
        $error = new MessageBag([
            'title' => '操作失败'
        ]);
        return back()->with(compact('error'));
    }

    /*添加精选
     *
     * */
    public function addBest(Request $request)
    {
        $request = $request->all();
        $aid = $request['aid'];
        $op_title = $request['title'];
        $info = dbArticle::getArticleInfo($aid);
        $best_info = BestArticle::get("*", ["AND" => ["aid" => $aid]]);
        $recommend_info = RecommendArticle::getByAid($aid);
        //是否下发积分
        if ($info['is_example'] != 1 && $recommend_info['is_points'] == 0) {
            $event_name = PointConfig::POINT_TYPE_GREAT_ARTICLE;
            $point = 5000;
            $source = 'admin';
            $request_id = $source . $event_name . $aid . date('YmdHis', time());
            $msg['obj_id'] = $aid;
            $msg['detail'] = "整屋加编辑精选";
            $ext_info = json_encode($msg, JSON_UNESCAPED_UNICODE);
            PointClient::awardPoint(IdParse::getUid($aid), $point, $event_name, $request_id, $source, $ext_info);
            //发消息
            Queue::insertQueue('queue/Sysmsg/Send',
                [
                    'msgCode' => 121,
                    'to_uid' => IdParse::getUid($aid),
                    'msgParams' => [
                        'link' => HhzNiceLivingUrl::getArticleDetailLink($aid),
                        'article_id' => $aid
                    ]
                ], Queue::QUEUE_DORAEMON
            );
        }

        // 查询更新之前此整屋的质量
        $qualityLastTime = -1;
        if ($info['admin_score'] != 80) {
            $qualityLastTime = $info['admin_score'];
        }

        //想库里添加数据
        $update_data = [
            'admin_score' => 80,
            'status' => dbArticle::STATUS_SUCCESS,
            'admin_id' => Admin::user()->id,
            'admin_name' => Admin::user()->name,
            'is_example' => 1,
            'check_time' => time(),
        ];
        $rs = dbArticle::updateArticle($aid, $update_data);
        //精选
        if ($best_info && is_array($best_info)) {
            BestArticle::updateArticle($aid, ['title' => $op_title, 'status' => BestArticle::STATUS_SUCCESS]);
        } else {
            //精选库
            BestArticle::insert([
                'aid' => $aid,
                'uid' => IdParse::getUid($aid),
                'title' => $op_title,
                'admin_id' => Admin::user()->id,
                'addtime' => time(),
                'status' => BestArticle::STATUS_SUCCESS
            ]);
        }
        if ($recommend_info && is_array($recommend_info)) {
            RecommendArticle::updateArticle($aid, ['admin_id' => Admin::user()->id, 'edittime' => time(), 'is_points' => RecommendArticle::IS_POINT]);
        } else {
            //存储下发积分消息信息
            RecommendArticle::insertData([
                'uid' => IdParse::getUid($aid),
                'aid' => $aid,
                'admin_id' => Admin::user()->id,
                'addtime' => time(),
                'is_points' => RecommendArticle::IS_POINT
            ]);
        }
        Queue::insertQueue("TotalArticle/updateTotalArticle", ['article_id' => $aid]);
        cArticle::delete($aid);
        Queue::insertQueue('Article/updateSolr', ['article_id' => $aid]);
        Queue::insertQueue('Article/seriesArticle', ['article_id' => $aid]);
        self::pushLevel3Standard($aid, $qualityLastTime, 80);
        //绑定设计师计数
        sBindDesignerArticle::addBindArticle($aid);
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        return redirect('/admin/article/select/bestForm/' . $aid)->with(compact('success'));
    }


    /*删除精选
     * */
    public function delBest(Request $request, $aid)
    {
        try {
            //删除精选
            $info = dbArticle::getInfosByAids($aid);
            if (empty($info)) {
                throw new \Exception('文章不存在！');
            }

            $recommend_info = RecommendArticle::getByAid($aid);
            //精选
            BestArticle::updateArticle($aid, ['status' => BestArticle::STATUS_DELETE, 'admin_id' => Admin::user()->id]);
            if ($recommend_info['is_del_points'] == 0) {
                RecommendArticle::updateArticle($aid, ['admin_id' => Admin::user()->id, 'edittime' => time(), 'is_del_points' => RecommendArticle::IS_POINT, 'status' => RecommendArticle::STATUS_DELETE]);
                //取消积分和下发消息
                $event_name = PointConfig::POINT_TYPE_UNGREAT_ARTICLE;
                $point = '5000';
                $source = 'admin';
                $request_id = $source . $event_name . $aid . date('YmdHis', time());
                $msg['obj_id'] = $aid;
                $msg['detail'] = "整屋取消编辑精选";
                $ext_info = json_encode($msg, JSON_UNESCAPED_UNICODE);
                PointClient::deductPoint(IdParse::getUid($aid), $point, $event_name, $request_id, $source, $ext_info);
                //发消息
            }
            //更新文章分数
            $update_data = [
                'admin_score' => 70,
                'status' => dbArticle::STATUS_SUCCESS,
                'admin_id' => Admin::user()->id,
                'admin_name' => Admin::user()->name,
                'is_example' => 0,
                'check_time' => time(),
            ];
            $rs = dbArticle::updateArticle($aid, $update_data);
            if ($rs) {
                Queue::insertQueue("TotalArticle/updateTotalArticle", ['article_id' => $aid]);
                cArticle::delete($aid);
                Queue::insertQueue('Article/updateSolr', ['article_id' => $aid]);
                self::pushLevel3Standard($aid, 80, 70);
                $status = true;
                $message = "操作成功";
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        return response()->json(compact('status', 'message'));
    }


    /*仅自己可见
     * */
    public function setPrivate(Request $request, $aid)
    {

        try {
            //删除精选
            $info = dbArticle::getInfosByAids($aid);
            if (empty($info)) {
                throw new \Exception('文章不存在！');
            }
            $rs = dbArticle::updateArticle($aid, ['status' => dbArticle::STATUS_PRIVATE, 'admin_score' => 4, 'admin_id' => Admin::user()->id, 'admin_name' => Admin::user()->name]);

            $upData['status'] = 11;
            MyArticleList::updateByObjId($aid, ['status' => MyArticleList::STATUS_PRIVATE]);

            // 删除正在发生
            Queue::insertQueue('Api/delFeedByObjId', array(
                'obj_id' => $aid
            ));
            //图片信息
            $note_info = dbPhoto::getPhotosByUidWithAid(IdParse::getUid($aid), $aid, []);

            if ($note_info && is_array($note_info)) {
                $note_ids = array_column($note_info, 'id');
                $this->setNoteprivate($note_ids);
            }
            //图片设置为仅自己可见
            if ($rs) {
                Queue::insertQueue("TotalArticle/updateTotalArticle", ['article_id' => $aid]);
                cArticle::delete($aid);
                Queue::insertQueue('Article/updateSolr', ['article_id' => $aid]);
                $status = true;
                $message = "操作成功";
            } else {
                $status = false;
                $message = "操作失败";
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        return response()->json(compact('status', 'message'));
    }


    /*设置图片信息仅自己可见
     *
     * */
    public function setNoteprivate($note_ids = [])
    {
        // 整屋设置为仅自己可见之后，需要将相关note也设置为仅自己可见
        if ($note_ids && is_array($note_ids)) {
            foreach ($note_ids as $note_id) {
                $data = [];
                $data['show_status'] = dbPhoto::SHOW_STATUS_PRIVATE;
                $data['edittime'] = time();
                $rs = dbPhoto::updatePhotoById($note_id, $data);

                // 修改note remark
                NoteHandle::remarkNote($note_id, AdmNoteRemark::REMARK_PRIVATE_SELF);
                // 添加操作日志
                AdmNote::auditLog($note_id, dbPhoto::QUALITY_LOW, Admin::user()->name, AdmNoteOutlineLog::AUDIT_CHANNEL_ARTICLE);


                // 删除正在发生
                Queue::insertQueue('Api/delFeedByObjId', array(
                    'obj_id' => $note_id
                ));
                // 删除图片信息缓存
                cPhotos::delete($note_id);

                Queue::insertQueue('Photo/afterAudit', array(
                    'photo_id' => $note_id
                ));
            }
        }
    }


    /*恢复全体可见
     *
     * */
    public function recoverPrivateOfArticle(Request $request, $aid)
    {
        try {
            $article_info = dbArticle::getArticleByIds($aid);
            if (!$article_info && !is_array($article_info)) {
                throw new \Exception("The article isn't existent");
            }
            $article_data = array();
            $article_data['edittime'] = time();
            $article_data['admin_score'] = 0;
            $article_data['status'] = dbArticle::STATUS_SUCCESS;
            dbArticle::updateArticle($aid, $article_data);

            $upData['status'] = 1;
            MyArticleList::updateByObjId($aid, $upData);

            // 添加到队列，更新搜索图片
            $note_info = dbPhoto::getPhotosByUidWithAid(IdParse::getUid($aid), $aid, []);
            if ($note_info && is_array($note_info)) {
                $note_ids = array_column($note_info, 'id');
                $this->recoverOfPhoto($note_ids);
            }
            //添加到队列，更新搜索图片
            // 删除文章信息缓存
            cArticle::delete($aid);

            // 更新文章solr
            Queue::insertQueue('Article/updateSolr', array(
                'article_id' => $aid
            ));
            Queue::insertQueue('TotalArticle/updateTotalArticle', array(
                'article_id' => $aid
            ));
            $status = true;
            $message = '操作成功';
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        return response()->json(compact('status', 'message'));
    }

    /*
     *
     * */
    public function recoverOfPhoto($note_ids)
    {
        if ($note_ids && is_array($note_ids)) {
            foreach ($note_ids as $note_id) {

                $photo_info = dbPhoto::getPhoto($note_id);
                if (!$photo_info && !is_array($photo_info)) {
                    throw new \Exception("The photo isn't existent");
                }

                $photo_data = array();
                $photo_data['id'] = $note_id;
                $photo_data['status'] = dbPhoto::STATUS_SUCCESS;
                $photo_data['admin_score'] = 0;
                dbPhoto::updatePhotoById($note_id, $photo_data);
                // 修改note remark
                NoteHandle::remarkNote($note_id, "");

                // 删除图片信息缓存
                cPhotos::delete($note_id);
                // 更新图片solr
                Queue::insertQueue('Photo/afterAudit', array(
                    'photo_id' => $note_id
                ));
            }
        }
    }


    /*删除
     * */
    public function del(Request $request, $aid)
    {
        try {
            $info = dbArticle::getArticleInfo($aid);
            if (empty($info)) {
                throw new \Exception('文章不存在！');
            }
            //绑定设计师计数
            sBindDesignerArticle::addBindArticle($aid);
            $rs = dbArticle::updateArticle($aid, ['status' => dbArticle::STATUS_DELETE, 'admin_id' => Admin::user()->id, 'admin_name' => Admin::user()->name]);
            if (empty($rs)) {
                throw new \Exception('Article表操作失');
            }
            //bestArticle
            $best_info = BestArticle::getOneArticle($aid);
            if ($best_info) {
                $rs = BestArticle::updateArticle($aid, ['status' => BestArticle::STATUS_DELETE, 'admin_id' => Admin::user()->id]);
                if (empty($rs)) {
                    throw new \Exception('BestArticle表操作失败');

                }
            }
            //myarticle
            $article_list = MyArticleList::getInfoByObjId($aid);
            if ($article_list) {
                $rs = MyArticleList::updateByObjId($aid, ['status' => MyArticleList::STATUS_DELETE]);
                if (empty($rs)) {
                    throw new \Exception('MyArticleList表操作失败');
                }
            }
            //recommend article
            $recommend_info = RecommendArticle::getByAid($aid);
            if ($recommend_info['is_del_points'] == 0) {
                //扣除积分
                $uid = IdParse::getUid($aid);
                $event_name = PointConfig::POINT_TYPE_UNGREAT_ARTICLE;
                $point = '5000';
                $source = 'admin';
                $request_id = $source . $event_name . $aid . date('YmdHis', time());
                $msg['obj_id'] = $aid;
                $msg['detail'] = "整屋删除导致取消编辑精选";
                $ext_info = json_encode($msg, JSON_UNESCAPED_UNICODE);
                PointClient::deductPoint($uid, $point, $event_name, $request_id, $source, $ext_info);
                $rs = RecommendArticle::updateArticle($aid, ['status' => RecommendArticle::STATUS_DELETE, 'admin_id' => Admin::user()->id]);
                if (empty($rs)) {
                    throw new \Exception('RecommendArticle表操作失败');
                }
            }

            if ($rs) {
                //创作者中心3.0-删除整屋
                $oldWikiId = ObjRelateWiki::getRelWikiForArticleList($aid, '', 1);
                $remarks = ['now_quality' => $info['admin_score'], 'old_wiki_id' => $oldWikiId];
                CommunityQueue::insertQueue(tGrowthConfig::MQ_QUEUE_URL, [
                    'event_name' => tGrowthConfig::CREAT_GROWTH_ARTICLE_DEL,
                    'obj_id' => $aid,
                    'uid' => IdParse::getUid($aid),
                    'remarks' => json_encode($remarks, JSON_UNESCAPED_UNICODE),
                ], \Doraemon\amqp\CommunityQueue::QUEUE_COMMUNITY);

                Log::info('后台删除整屋', [Admin::user()->name, $aid]);
                Queue::insertQueue("TotalArticle/delArticleById", ['article_id' => $aid]);
                cArticle::delete($aid);
                Queue::insertQueue('Article/delArticle', ['article_id' => $aid]);
                $status = true;
                $message = "操作成功";
            } else {
                $status = false;
                $message = "操作失败";
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        return response()->json(compact('status', 'message'));
    }

    /*一键复审
     *
     * */
    public function reCheck(Request $request, $aid)
    {
        try {
            if (empty($aid)) {
                throw new \Exception('文章ID传入失败！');
            }
            $rs = dbArticle::updateArticle($aid, ['status' => dbArticle::STATUS_SUCCESS, 'admin_id' => Admin::user()->id, 'check_time' => time(), 'admin_name' => Admin::user()->name]);
            if ($rs) {
                Queue::insertQueue("TotalArticle/updateTotalArticle", ['article_id' => $aid]);
                cArticle::delete($aid);
                Queue::insertQueue('Article/updateSolr', ['article_id' => $aid]);
                $status = true;
                $message = "操作成功";
            } else {
                $status = false;
                $message = "操作失败";
            }

        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        return response()->json(compact('status', 'message'));

    }


    /**
     * 常用语编辑
     */
    public function editNormalWord(Content $content)
    {
        $tab = new Tab();
        $tab->addLink('整屋列表', url('/admin/article/select/index'));
        $tab->addLink('违规整屋', url('/admin/article/select/draftlist'));
        $tab->add("编辑常用语", $this->editNormalWordAction(), true);

        return $content
            ->header('反馈管理')
            ->breadcrumb(
                ['text' => "常用语编辑"]
            )
            ->body($tab);
    }

    /**
     * 常用语编辑--信息展示
     */
    private function editNormalWordAction()
    {
        $info = $this->NormalWord();
        $form = new Form($info);
        $form->textarea('text', '常用语')->help('请用换行隔开每条常用语');
        $form->action('/admin/article/select/normalword/list/save');
        return $form->render();
    }

    /**
     * 常用语编辑--信息保存
     */
    public function saveNormalWord(Request $request)
    {
        $text = $request->input('text', '');
        $result = $this->NormalWord($text);

        if ($result) {
            return back()->with('success', new MessageBag([
                'title' => '操作成功'
            ]));
        } else {
            return back()->with('error', new MessageBag([
                'title' => '操作失败'
            ]));
        }

    }

    /*Normarl word
     *
     * */
    public function NormalWord($text = null)
    {
        if ($text) {
            $rs = file_put_contents(self::NORMAL_WORD, $text);
            if ($rs) {
                return true;
            } else {
                return false;
            }
        } else {
            $word = file_get_contents(self::NORMAL_WORD);
            return [
                'text' => $word,
            ];
        }
    }

    /*导出数据
     *
     * */
    public function exportNormarlData(Request $request)
    {
        $request = $request->all();

        $pageSize = 1500;
        $page = 1;
        if (isset($request['Find_group']) && $request['Find']) {
            $request[FilterConfig::ARTICLE_FIND_GROUP[$request['Find_group']]] = $request['Find'];
        }
        $request['page_size'] = $pageSize;
        $request['page'] = $page;
        $object = new ArticleSearch($request);
        $solr_list = Schedule::getList($object);
        $article_ids = $solr_list['rows'] ?: [];
        $list = [];
        if ($article_ids && is_array($article_ids)) {
            $list = dbArticle::select("*", [
                "AND" => [
                    "aid" => $article_ids
                ],
            ]);
            $list = array_combine(array_column($list, 'aid'), $list);
            $info = sArticle::getArticleBasicInfos($article_ids);
        }
        $row = $this->formateArticleInfo($info, $list);
        if (!empty($row)) {
            $subject['list'] = $row;
            $subject['total'] = count($row);
        } else {
            $subject['list'] = [];
            $subject['total'] = 0;
        }
        $reason = '整屋信息';
        $header = ['aid', 'uid', '昵称', '用户身份', '地区', '预算', '面积', '阅读', '点赞', '评论', '收藏', '发布时间', '居室', '分数'];
        $letter = range('A', 'N');
        $excelObj = new DownExcel();
        $excelObj->setFileName($reason);
        $excelObj->setSheetTitle($reason);

        //设置列宽
        $widths = ['A' => 45, 'B' => 100];
        $excelObj->setWidth($widths);
        //默认单元格居中
        $excelObj->setDefaultStyleAlignment();
        $excelObj->freezePane('A1');//冻结窗口
        $excelObj->setTextFormat('A');
        $excelObj->setTextFormat('B');
        foreach ($header as $key => $value) {
            //设置字体
            $excelObj->setFrontName($letter[$key]);
            //设置加粗
            $excelObj->setFrontBold("$letter[$key]1");
            //设置大小
            $excelObj->setFrontSize($letter[$key]);
        }
        $excelObj->create($subject['list'], $header);
    }


    /*直播房间号
     *
     * */
    public function setLiveRoom(Request $request, Content $content, $aid)
    {
        Admin::style('.main-header {display:none;}');
        $info = dbArticle::getInfoByAid($aid);
        if ($info['extend']) {
            $extend_info = json_decode($info['extend'], true) ?: [];
            if ($extend_info && is_array($extend_info)) {
                $room_ids = $extend_info['live_room_ids'] ?: [];
                if ($room_ids && is_array($room_ids)) {
                    $info['room_ids'] = implode(',', $room_ids);
                }
            }
        }

        $info = $info ?: [];
        $info['aid'] = $aid;
        $form = new Form($info);
        $form->hidden('aid');
        $form->text('room_ids', '房间号')->help("用逗号分割多个直播room_id");
        $form->disableReset();
        $form->action('/admin/article/select/addLiveRoom');
        return $content->row($form->render());
    }


    /*添加直播房间号
     *
     * */
    public function addLiveRoom(Request $request)
    {
        $request = $request->all();
        $aid = $request['aid'];
        $info = dbArticle::getArticleInfo($aid);
        $room_ids = trim($request['room_ids']);
        if ($room_ids) {
            $room_ids = explode(",", $room_ids) ?: [];
            if ($room_ids && is_array($room_ids)) {
                $room_ids = array_unique(array_filter($room_ids));
            }
        } else {
            $room_ids = [];
        }
        $update_data = [
            'extend' => json_encode(['live_room_ids' => array_values($room_ids)])
        ];

        $rs = dbArticle::updateArticle($aid, $update_data);
        if ($rs) {
            Queue::insertQueue("TotalArticle/updateTotalArticle", ['article_id' => $aid]);
            cArticle::delete($aid);
            Queue::insertQueue('Article/updateSolr', ['article_id' => $aid]);
        }
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        return redirect('/admin/article/select/setLiveRoom/' . $aid)->with(compact('success'));
    }


    /*format article info
     * */
    public function formateArticleInfo($article_info, $hash_score_info)
    {
        $list = [];
        $UserProfileList = new UserProfileListController();
        if ($article_info && is_array($article_info)) {
            foreach ($article_info as $info) {
                $list[] = [
                    'aid' => $info['article_id'],
                    'uid' => $info['user_info']['uid'],
                    'nick' => $info['user_info']['nick'],
                    'user_type' => $UserProfileList->FormateType($info['user_info']['uid'], $info['user_info']['type']),
                    // 'title' => Filter::filterEmoji($info['article_info']['title']),
                    'area' => $info['article_info']['area_name'],
                    'stuff' => $info['article_info']['house_stuff'],
                    'size' => $info['article_info']['house_size'],
                    'read' => $info['counter']['read'] ?: 0,
                    'like' => $info['counter']['like'] ?: 0,
                    'comments' => $info['counter']['comments'] ?: 0,
                    'fav' => $info['counter']['favorite'] ?: 0,
                    'publish_time' => date("Y-m-d H:i:s", $info['article_info']['publish_time']),
                    'room' => FilterConfig::ROOM[$info['article_info']['house_construction']] ?: '无',
                    'score' => $hash_score_info[$info['article_id']]['admin_score'] ? FilterConfig::SCORE_CONTENT[$hash_score_info[$info['article_id']]['admin_score']] : '未打分'

                ];

            }

        }

        return $list;

    }

    /*设置scirpt
     *
     * */
    private function setScript()
    {
        return <<<SCRIPT
       
       $('.delbest').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要取消精选么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/article/select/delBest/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.status == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
        //仅自己可见
         $('.setPrivate').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要设置仅自己可见么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/article/select/setPrivate/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.status == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
        //删除
         $('.del').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要删除么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/article/select/del/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.status == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
SCRIPT;
    }

    //评论弹窗
    public function commentPopup()
    {
        return <<<SCRIPT
           
            $('.addComment').unbind('click').click(function() {
                var id = $(this).data('id');
                //iframe窗
                layer.open({
                    type: 2,
                    title: '运营评论',
                    shadeClose: true,
                    shade: 0.4,
                    maxmin: true,
                    area: ['700px', '600px'],
                    content: 'comment/'+id,
                    end: function () {
                        $.ajax({type:"get",url:"comment/check/"+id,success:function(data){
                      
                            if(data != '') {
                                $('#'+id).html(data+"已评论");
                                $('#'+id).addClass('btn-success');
                                $('#'+id).css('color','#FFFFFF');
                                $('#'+id).attr('disabled', 'disabled');
                            }
                        }});
                    }
                });
		    });
SCRIPT;
    }

    public function checkComment(Request $request, $note_id)
    {
        $rs = '';
        $hasComment = AdminAccountOperate::getByObjId($note_id, AdminAccountOperate::ACCOUNT_TYPE_COMMENT, self::OBJ_TYPE);
        if ($hasComment && is_array($hasComment)) {
            $rs = (string)Admin::user()->find($hasComment['admin_id'])->name;
        }
        return $rs;
    }

    //添加评论弹窗
    public function addCommentPop(Request $request, \App\Admin\Extensions\WorkContent $content, $id)
    {
        $request = $request->all();
        return $content
            ->header('运营评论')
            ->body(self::addCommentAction($request, $id));
    }

    public function addCommentAction($request, $id)
    {
        $data = [
            'obj_id' => $id,
            'content' => ''
        ];
        $account = [];
        $accounts = AdminAccount::getByAdminId(Admin::user()->id);
        if ($accounts && is_array($accounts)) {
            $user_infos = Member::getUsers($accounts);
            if ($user_infos && is_array($user_infos)) {
                foreach ($user_infos as $user_info) {
                    $account[$user_info['uid']] = $user_info['nick'];
                }
            }
        }
        $form = new Form($data);
        $form->display('obj_id', '内容id');
        $form->textarea('content', '评论内容')->setWidth(10, 2)->required('不能为空')->help('请输入内容内容');
        $form->select('account', '选择发布账号')->options($account)->required('必选');
        $form->html("<a href='" . $id . "/commentaccount' class='btn btn-small btn-sm'>账号管理</a>");
        $form->action('/admin/article/select/comment/' . $id . '/save');

        return $form->render();
    }

    //添加评论
    public function saveComment(Request $request, $id)
    {
        $is_owner = 0;
        $request = $request->all();
        $obj_uid = dbArticle::getArticle($id)['uid'];
        if ($obj_uid == $request['account']) {
            $is_owner = 1;
        }
        $data = [
            "content" => trim($request['content']),
            "obj_id" => $id,
            "obj_type" => self::OBJ_TYPE,
            "type" => 1,
            "uid" => $request['account'],
            "to_uid" => 0,
            "addtime" => time(),
            "add_ip" => Ip::getClientIp(),
            "status" => 1,
            "admin_id" => Admin::user()->id,
            "is_owner" => $is_owner,
        ];
        $has_comment = AdminAccountOperate::getByObjId($data['obj_id'], AdminAccountOperate::ACCOUNT_TYPE_COMMENT, $data['obj_type']);
        if ($has_comment) {
            $error = new MessageBag([
                'title' => '评论失败,此内容已有运营评论'
            ]);
            return redirect('/admin/article/select/comment/' . $data['obj_id'])->with(compact('error'));
        }
        $result = DbComment::addComment($data);
        Queue::insertQueue('CommentDig/afterComment', array(
            'obj_id' => $data['obj_id'],
            'uid' => $data['uid'],
            'comment' => $data['content'],
            'cmt_id' => $result,
            'time' => time(),
        ));

        //更新es
        Queue::insertQueue('Comment/addComment', array(
            'obj_id' => $data['obj_id'],
            'cmt_id' => $result
        ));

        // 返回结果
        if ($result) {
            AdminAccountOperate::addData([
                "operate_type" => AdminAccountOperate::ACCOUNT_TYPE_COMMENT,
                "uid" => $data['uid'],
                "admin_id" => Admin::user()->id,
                "addtime" => date('Y-m-d H:i:s', time()),
                "obj_id" => $data['obj_id'],
                "obj_type" => self::OBJ_TYPE,
                "content" => $data['content'],
                'comment_id' => $result
            ]);
            $this->_articleHandle($data, $result);
            HaveRecommend::setHaveInteract($data['uid'], $data['obj_id']);
            $success = new MessageBag([
                'title' => '评论成功'
            ]);
            return redirect('/admin/article/select/comment/' . $data['obj_id'])->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '评论失败'
            ]);
            return redirect('/admin/article/select/comment/' . $data['obj_id'])->with(compact('error'));
        }

    }

    public function _articleHandle($data, $comment_id)
    {
        // 计数器图片评论加1
        ArticleCounter::increaseArticleCounter($data['obj_id'], ArticleCounter::ACT_COMMENT);
        ArticleCounter::increaseArticleCounter($data['obj_id'], ArticleCounter::ACT_MASTER_COMMENT);

        $aQueueData = array(
            'act' => 'comment',
            'article_id' => $data['obj_id'],
            'act_uid' => $data['uid'],
            'cmt_id' => $comment_id,
            'reply_uid' => $data['to_uid'],
            'from_platform' => $data['from_platform'],
        );
        Queue::insertQueue('Article/interaction', $aQueueData);
    }

    //评论账号列表
    public function commentAccount(Request $request, \App\Admin\Extensions\WorkContent $content)
    {
        $request = $request->all();
        return $content
            ->body(self::commentAccountList($request));

    }

    public static function commentAccountList($request)
    {
        $account_list = AdminAccount::getAllByAdminId(Admin::user()->id);
        $user_infos = [];
        if ($account_list && is_array($account_list)) {
            $uids = array_column($account_list, 'uid');
            if ($uids && is_array($uids)) {
                $user_infos = Member::getUsers($uids);
            }
            foreach ($account_list as &$account_info) {
                $account_info['nick'] = (string)$user_infos[$account_info['uid']]['nick'];
            }
        }

        $gridModel = new pGridDataModel($account_list, count($account_list), []);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disablePagination();
            $grid->disableFilter();
            $grid->disableActions();
            $grid->disableRowSelector();
            $grid->column('id');
            $grid->column('uid', '用户id');
            $grid->column('nick', '用户昵称');
            $grid->column('addtime', '添加时间');
        });
        $list = $listGrid->render();
        return $list;
    }

    //添加运营评论账号
    public function addCommentAccount(Request $request, \App\Admin\Extensions\WorkContent $content, $id)
    {
        return $content
            ->body(self::commentEditAction($request, $id));
    }

    public function commentEditAction($request, $id)
    {
        $form = new Form([]);
        $form->number('uid', 'uid')->required('必填');
        $form->action('/admin/article/select/comment/' . $id . '/commentaccount/save');
        return $form->render();
    }

    public function commentAccountSubmit(Request $request, $id)
    {
        $request = $request->all();
        $uid = (int)$request['uid'];
        $admin_id = Admin::user()->id;
        $has_account = AdminAccount::getByAdminIdAndUid($uid, $admin_id);
        if ($uid && !$has_account) {
            $data = [
                'uid' => $uid,
                'admin_id' => $admin_id,
                'account_type' => AdminAccount::ACCOUNT_TYPE_COMMENT,
                'addtime' => date('Y-m-d H:i:s', time()),
                'account_status' => AdminAccount::STATUS_NORMAL
            ];
            AdminAccount::addData($data);
            $success = new MessageBag([
                'title' => '添加成功'
            ]);
            return redirect("/admin/article/select/comment/{$id}/commentaccount")->with(compact('success'));
        }
        $error = new MessageBag([
            'title' => '添加失败'
        ]);
        return redirect("/admin/article/select/comment/{$id}/commentaccount")->with(compact('error'));

    }

    //运营点赞
    public function adminLike()
    {
        return <<<SCRIPT
            $('.addLike').click(function() {
                var id = $(this).data('id');
                $.ajax({type:"get",url:"like/"+id,success:function(data){
                    if(data != '') {
                        $('#like'+id).html(data+"已点赞");
                        $('#like'+id).addClass('btn-success');
                        $('#like'+id).css('color','#FFFFFF');
                        $('#like'+id).attr('disabled', 'disabled');
                    }
                }});
            });
          
SCRIPT;
    }

    public function saveLike($id)
    {
        $rs = '';
        $hasLike = AdminAccountOperate::getByObjId($id, AdminAccountOperate::ACCOUNT_TYPE_LIKE, self::OBJ_TYPE);
        if ($hasLike) {
            $rs = Admin::user()->find($hasLike['admin_id'])->name;
        } else {
            AutoAction::autoLike($id, AutoAction::SOURCE_ADMIN);
            AdminAccountOperate::addData([
                "operate_type" => AdminAccountOperate::ACCOUNT_TYPE_LIKE,
                "uid" => (int)0,
                "admin_id" => Admin::user()->id,
                "addtime" => date('Y-m-d H:i:s', time()),
                "obj_id" => $id,
                "obj_type" => self::OBJ_TYPE,
                "content" => ''
            ]);
            $hasLike = AdminAccountOperate::getByObjId($id, AdminAccountOperate::ACCOUNT_TYPE_LIKE, self::OBJ_TYPE);
            if ($hasLike) {
                $rs = Admin::user()->find($hasLike['admin_id'])->name;
            }
        }
        return $rs;
    }

    //复制H5链接
    public function copyUrl($id)
    {
        return Hhzurl::h5BangyangShow($id);
    }

    public function adminCopy()
    {
        return <<<SCRIPT
        $('.copyH5').click(function() {
            var id = $(this).data('id');
            $.ajax({type:"get",url:"copy/"+id,success:function(url){
            var tempInput = document.createElement("input");
            tempInput.value = url;
            document.body.appendChild(tempInput);
            tempInput.select();
            document.execCommand("copy");
            document.body.removeChild(tempInput);
            }});
        });
        $('.addBusiness').click(function() {
                var id = $(this).data('id');
                console.log($(this).hasClass('addBusiness'));
                 if($(this).hasClass('btn-success')) {
                    type = 'remove';
                } else {
                    type = 'add';
                }
                $.ajax({type:"get",url:"business/"+id+"/"+type,success:function(data){
                    if(data) {
                       if (type == 'remove'){
                            $('#business'+id).removeClass('btn-success');
                            $('#business'+id).addClass('btn-default');
                            $('#business'+id).css('color','#444');                        
                       }else{
                        $('#business'+id).addClass('btn-success');
                        $('#business'+id).css('color','#FFFFFF');
                       } 
                         toastr.success('修改成功', null, {
                            timeOut : 1000
                        });  
                    }else{
                     toastr.success('修改失败', null, {
                            timeOut : 1000
                        });
                    }
                }});
            });
            
            $('.addDisplayBusiness').click(function() {
                var id = $(this).data('id');
                console.log($(this).hasClass('addDisplayBusiness'));
                 if($(this).hasClass('btn-success')) {
                    type = 'remove';
                } else {
                    type = 'add';
                }
                $.ajax({type:"get",url:"displayBusiness/"+id+"/"+type,success:function(data){
                    if(data) {
                       if (type == 'remove'){
                            $('#displayBusiness'+id).removeClass('btn-success');
                            $('#displayBusiness'+id).addClass('btn-default');
                            $('#displayBusiness'+id).css('color','#444');                        
                       }else{
                        $('#displayBusiness'+id).addClass('btn-success');
                        $('#displayBusiness'+id).css('color','#FFFFFF');
                       } 
                         toastr.success('修改成功', null, {
                            timeOut : 1000
                        });  
                    }else{
                     toastr.success('修改失败', null, {
                            timeOut : 1000
                        });
                    }
                }});
            });
SCRIPT;
    }

    /**
     * @param $id
     * @param $type
     * @return int|mixed|string
     */
    public function editBusiness($id, $type)
    {
        $info = ContentSignExtend::getExtendInfoByNoteIds($id);

        if ($type == "add") {
            $data = [
                "obj_id" => $id,
                "is_business" => ContentSignExtend::IS_BUSINESS,
                "admin_id" => Admin::user()->id,
                "obj_type" => IdParse::getType($id),
            ];
            if ($info) {
                $data["edittime"] = date('Y-m-d H:i:s', time());
                $rs = ContentSignExtend::upateExtendInfo($data, ['obj_id' => $id]);
            } else {
                $data["addtime"] = date('Y-m-d H:i:s', time());
                $data["obj_type"] = IdParse::getType($id);
                $rs = ContentSignExtend::addExtendInfo($data);
            }
            if (!empty($rs)) {
                CommunityQueue::insertQueue('queue/Communitymcn/businesstoes', [
                    'id' => $id,
                    'business' => self::ES_BUSINESS['SOFT_BUSINESS']
                ], CommunityQueue::QUEUE_COMMUNITY);
            }
        } else {
            $data = [
                "obj_id" => $id,
                "is_business" => ContentSignExtend::NOT_BUSINESS,
                "admin_id" => Admin::user()->id,
                "obj_type" => IdParse::getType($id),
            ];
            if ($info) {
                $data["edittime"] = date('Y-m-d H:i:s', time());
                $rs = ContentSignExtend::upateExtendInfo($data, ['obj_id' => $id]);
            }
            if (!empty($rs)) {
                CommunityQueue::insertQueue('queue/Communitymcn/businesstoes', [
                    'id' => $id,
                    'business' => self::ES_BUSINESS['NOT_BUSINESS']
                ], CommunityQueue::QUEUE_COMMUNITY);
            }
        }
        return $rs;
    }

    public function displayBusiness($id, $type)
    {
        $info = ContentSignExtend::getExtendInfoByNoteIds($id);

        if ($type == "add") {
            $data = [
                "obj_id" => $id,
                "is_display_business" => ContentSignExtend::IS_BUSINESS,
                "admin_id" => Admin::user()->id,
                "obj_type" => IdParse::getType($id),
            ];
            if ($info) {
                $data["edittime"] = date('Y-m-d H:i:s');
                $rs = ContentSignExtend::upateExtendInfo($data, ['obj_id' => $id]);
            } else {
                $data["addtime"] = date('Y-m-d H:i:s', time());
                $data["obj_type"] = IdParse::getType($id);
                $rs = ContentSignExtend::addExtendInfo($data);
            }
            if (!empty($rs)) {
                CommunityQueue::insertQueue('queue/Communitymcn/businesstoes', [
                    'id' => $id,
                    'business' => self::ES_BUSINESS['HARD_BUSINESS']
                ], CommunityQueue::QUEUE_COMMUNITY);
            }
        } else {
            $data = [
                "obj_id" => $id,
                "is_display_business" => ContentSignExtend::NOT_BUSINESS,
                "admin_id" => Admin::user()->id,
                "obj_type" => IdParse::getType($id),
            ];
            if ($info) {
                $data["edittime"] = date('Y-m-d H:i:s');
                $rs = ContentSignExtend::upateExtendInfo($data, ['obj_id' => $id]);
            }
            if (!empty($rs)) {
                CommunityQueue::insertQueue('queue/Communitymcn/businesstoes', [
                    'id' => $id,
                    'business' => self::ES_BUSINESS['NOT_BUSINESS']
                ], CommunityQueue::QUEUE_COMMUNITY);
            }
        }
        return $rs;
    }

//    // 投入等级判断队列
//    private static function pushLevelStandard($aid, $qualityLastTime)
//    {
//        CommunityLevelQueue::insertQueue('queue/creators/levelStandard', [
//            'uid' => IdParse::getUid($aid),
//            'obj_id' => $aid,
//            'event' => sLevelStandard::EVENT_ARTICLE_ADMIN_SCORE,
//            'is_join_brand' => sLevelStandard::NOTE_JOIN_BRAND_NO,
//            'quality_last_time' => $qualityLastTime,
//            'click_type' => 'system_creators_levelStandard'
//        ], CommunityLevelQueue::QUEUE_COMMUNITY);
//    }

    //创作者中心3.0-创作力整屋审核
    private static function pushLevel3Standard($aid, $oldQuality, $newQuality)
    {
        $remarks = ['old_quality' => $oldQuality, 'new_quality' => $newQuality];
        CommunityQueue::insertQueue(tGrowthConfig::MQ_QUEUE_URL, [
            'event_name' => tGrowthConfig::CREAT_GROWTH_ARTICLE,
            'obj_id' => $aid,
            'uid' => IdParse::getUid($aid),
            'remarks' => json_encode($remarks, JSON_UNESCAPED_UNICODE),
        ], CommunityQueue::QUEUE_COMMUNITY);
        //积分操作-评为精选增加积分
        if ($newQuality == Article::QUALITY_FEATURED) {
            CommunityQueue::insertQueue(PointConfig::MQ_QUEUE_URL, [
                'event_name' => PointConfig::ARTICLE_QUALITY_FEATURED,
                'obj_id' => $aid,
                'uid' => IdParse::getUid($aid),
                'type' => PointConfig::POINT_AWARD
            ], \Doraemon\amqp\CommunityQueue::QUEUE_COMMUNITY);
        }
    }
}